package com.alogic.cert.bc.builder;

import com.alogic.cert.bc.CertificateStoreImpl;
import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.cert.X509v3CertificateBuilder;

/**
 * 增加BasicConstraints
 *
 * @since 1.6.13.40 [20210306 duanyy] <br>
 */
public class AddBasicConstraints extends AbstractLogiclet {
    protected String pid = CertificateStoreImpl.XSCRIPT_OBJECT_ID;
    protected String $ca = "true";
    protected String $critical = "true";

    public AddBasicConstraints(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);
        pid = PropertiesConstants.getString(p,"pid",pid,true);

        $ca = PropertiesConstants.getRaw(p,"usage",$ca);
        $critical = PropertiesConstants.getRaw(p,"critical",$critical);
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, final LogicletContext ctx, final ExecuteWatcher watcher){
        X509v3CertificateBuilder builder  = ctx.getObject(pid);
        if (builder != null){
            try {
                builder.addExtension(Extension.basicConstraints , PropertiesConstants.transform(ctx,$critical,true),
                        new BasicConstraints(PropertiesConstants.transform(ctx,$ca,true)));
            }catch (Exception ex){
                log(ExceptionUtils.getStackTrace(ex));
            }
        }
    }
}